import time
import string
import random
import hashlib
from urllib.parse import quote
import requests
import sys
import base64


def jianhuang(image):
    with open('/home/chenyige/Desktop/t1.png', 'rb') as f:
        image_data = f.read()
    image_base64 = base64.b64encode(image_data)
    url = 'https://api.ai.qq.com/fcgi-bin/vision/vision_porn'
    request_data = {
        'app_id': 2124523006,
        # 当前秒级时间戳
        'time_stamp': int(time.time()),
        # 随机16位字符串
        # 'nonce_str': ''.join(random.sample(string.ascii_letters + string.digits, 16)),
        'nonce_str': 'f a577ce340859f9fe',
        # 图片URL
        # 'image_url': 'http://q1998r88n.bkt.clouddn.com/Fmq_ZLIioElgfyMuUbuU24dekKvm',
        'image': image_base64,
        # 待计算
        'sign': ''
    }
    # 按key进行字典升序排序
    sign_dict = {k: str(request_data[k]) for k in sorted(request_data)}
    # print(sign_dict)

    # 按URL键值对的格式拼接成字符串
    sign_str = ''
    for k, v in sign_dict.items():
        # sign_str = sign_str + k + '=' + v + '&'
        sign_str = sign_str + k + '=' + quote(v).upper() + '&'
    # 将应用密钥以app_key为键名，组成URL键值拼接到字符串T末尾
    app_key = 'qDof9bFZOtIHO670'
    sign_str = sign_str + 'app_key=' + app_key
    print(sign_str)
    # 对字符串进行MD5运算，将得到的MD5值所有字符转换成大写，得到接口请求签名
    m = hashlib.md5()
    m.update(sign_str.encode())
    sign_md5 = m.hexdigest().upper()
    print(sign_md5)
    # 将计算好的sign值放入请求字典中
    request_data['sign'] = sign_md5

    # 发送请求并获取响应
    response = requests.post(url, request_data)
    print(response)
    print(response.text)
    print(response.content)


if __name__ == '__main__':
    jianhuang('a')
